<?php

namespace app\User\controller;

use app\User\model\Role;
use think\Controller;
use think\Request;
use think\Validate;

class User extends Controller
{
    /*
     * 添加页面
     */
    public function index()
    {
        $role = Role::select();
        return view('index',['role'=>$role]);
    }

    /*
     * 添加方法
     */
    public function userAdd()
    {
        $data = input();
        array_shift($data);
        $rule = [
            'username'  => 'require',
            'password'  => 'require',
            'email'  => 'require',
            'status'  => 'require',

        ];
        $msg = [
            'username.require' => '用户名必须填写',
            'password.require' => '密码必须填写',
            'email.require' => '邮箱必须填写',
            'status.require' => '状态必须选择',
        ];
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return $this->error($validate->getError());
        }

        $res = \app\User\model\User::userAdd($data);//添加数据
        if (!$res){
            return $this->error('添加失败');
        }
        return $this->success('添加成功','userList');
    }
    /*
     * 分页展示
     */
    public function userList()
    {
        $data = \app\User\model\User::userList();  //两表查询

        return view('user_list',['data'=>$data]);
    }
    /*
     * 删除
     */
    public function userDel()
    {
        $id = input('id');
        $res = \app\User\model\User::where('id',$id)->find();
        if ($res['status']==0){
            return $this->error('状态为启用不能删除');
        }
        $res = \app\User\model\User::destroy($id);//当状态为不启用可以删除
        if (!$res){
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
}
